{% extends "base.html" %}

{% block title %}课程详情 - 学生选课系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-book me-2"></i>课程详情</h2>
    <div>
        <a href="/courses" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-1"></i>返回课程列表
        </a>
    </div>
</div>

<!-- 课程基本信息 -->
<div class="card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-0">课程基本信息</h5>
    </div>
    <div class="card-body">
        <div class="row" id="courseBasicInfo">
            <div class="text-center text-muted py-4">
                <i class="fas fa-spinner fa-spin fa-2x mb-2"></i>
                <p>加载中...</p>
            </div>
        </div>
    </div>
</div>

<!-- 选课学生列表 -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">选课学生列表</h5>
        <span class="badge bg-primary" id="enrollmentCount">0</span>
    </div>
    <div class="card-body">
        <div id="enrolledStudents">
            <div class="text-center text-muted py-4">
                <i class="fas fa-users fa-2x mb-2"></i>
                <p>暂无学生选课</p>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
// 获取URL中的课程ID
function getCourseIdFromUrl() {
    const pathParts = window.location.pathname.split('/');
    return pathParts[pathParts.length - 1];
}

// 页面加载时获取课程详情
document.addEventListener('DOMContentLoaded', function() {
    const courseId = getCourseIdFromUrl();
    if (courseId) {
        loadCourseDetail(courseId);
        
        // 只有管理员可以看到选课学生列表
        const userType = '{{ session.get("user_type", "") }}';
        if (userType === 'admin') {
            loadEnrolledStudents(courseId);
        } else {
            // 学生用户隐藏选课学生列表
            document.querySelector('.card:last-child').style.display = 'none';
        }
    }
});

// 加载课程详情
async function loadCourseDetail(courseId) {
    try {
        const response = await fetch(`/api/courses/${courseId}`);
        if (!response.ok) {
            throw new Error('获取课程详情失败');
        }
        const course = await response.json();
        renderCourseDetail(course);
    } catch (error) {
        console.error('加载课程详情失败:', error);
        alert('加载课程详情失败: ' + error.message);
    }
}

// 渲染课程详情
function renderCourseDetail(course) {
    const infoDiv = document.getElementById('courseBasicInfo');
    
    infoDiv.innerHTML = `
        <div class="col-md-6">
            <div class="mb-3">
                <label class="form-label text-muted">课程代码</label>
                <p class="fs-5 fw-bold">${course.course_code || '-'}</p>
            </div>
            <div class="mb-3">
                <label class="form-label text-muted">课程名称</label>
                <p class="fs-5">${course.course_name || '-'}</p>
            </div>
            <div class="mb-3">
                <label class="form-label text-muted">学分</label>
                <p class="fs-5">${course.credits || '0'} 学分</p>
            </div>
            <div class="mb-3">
                <label class="form-label text-muted">授课教师</label>
                <p class="fs-5">${course.teacher || '未设置'}</p>
            </div>
        </div>
        <div class="col-md-6">
            <div class="mb-3">
                <label class="form-label text-muted">上课时间</label>
                <p class="fs-5">${course.schedule || '未设置'}</p>
            </div>
            <div class="mb-3">
                <label class="form-label text-muted">上课地点</label>
                <p class="fs-5">${course.location || '未设置'}</p>
            </div>
            <div class="mb-3">
                <label class="form-label text-muted">课程容量</label>
                <p class="fs-5">
                    ${course.capacity > 0 ? 
                        `<span class="${course.enrolled >= course.capacity ? 'text-danger' : 'text-success'}">
                            ${course.enrolled || 0}/${course.capacity}
                        </span>` : 
                        '无限制'}
                </p>
            </div>
            <div class="mb-3">
                <label class="form-label text-muted">课程状态</label>
                <p class="fs-5">
                    <span class="badge ${course.capacity > 0 && course.enrolled >= course.capacity ? 'bg-danger' : 'bg-success'}">
                        ${course.capacity > 0 && course.enrolled >= course.capacity ? '已满员' : '可选课'}
                    </span>
                </p>
            </div>
        </div>
        ${course.description ? `
            <div class="col-12">
                <div class="mb-3">
                    <label class="form-label text-muted">课程描述</label>
                    <div class="card">
                        <div class="card-body">
                            <p class="mb-0">${course.description}</p>
                        </div>
                    </div>
                </div>
            </div>
        ` : ''}
        <div class="col-12 mt-3">
            <div class="d-flex gap-2">
                <!-- 只有管理员可以看到编辑和删除按钮 -->
                {% if session.get('user_type') == 'admin' %}
                <button class="btn btn-outline-primary" onclick="editCourse('${course._id}')">
                    <i class="fas fa-edit me-1"></i>编辑课程
                </button>
                <button class="btn btn-outline-danger" onclick="deleteCourse('${course._id}')">
                    <i class="fas fa-trash me-1"></i>删除课程
                </button>
                {% endif %}
            </div>
        </div>
    `;
}

// 加载选课学生列表
async function loadEnrolledStudents(courseId) {
    try {
        // 这里需要先获取所有学生选课记录，然后过滤出该课程的学生
        const response = await fetch('/api/students');
        if (!response.ok) {
            throw new Error('获取学生列表失败');
        }
        const allStudents = await response.json();
        
        // 获取该课程的选课记录
        const studentCoursesResponse = await fetch('/api/student-courses');
        let enrolledStudents = [];
        
        if (studentCoursesResponse.ok) {
            const allStudentCourses = await studentCoursesResponse.json();
            enrolledStudents = allStudentCourses
                .filter(sc => sc.course_id === courseId)
                .map(sc => {
                    const student = allStudents.find(s => s._id === sc.student_id);
                    return {
                        selection_id: sc._id,
                        student_id: sc.student_id,
                        course_id: sc.course_id,
                        selected_at: sc.selected_at,
                        status: sc.status || '已选',
                        student_name: student ? student.name : '未知学生',
                        student_grade: student ? student.grade : '',
                        student_major: student ? student.major : ''
                    };
                });
        }
        
        renderEnrolledStudents(enrolledStudents);
        
    } catch (error) {
        console.error('加载选课学生失败:', error);
    }
}

// 渲染选课学生列表
function renderEnrolledStudents(students) {
    const container = document.getElementById('enrolledStudents');
    const countBadge = document.getElementById('enrollmentCount');
    
    countBadge.textContent = students.length;
    
    if (students.length === 0) {
        container.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-users fa-2x mb-2"></i>
                <p>暂无学生选课</p>
            </div>
        `;
    } else {
        container.innerHTML = `
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>学生姓名</th>
                            <th>年级</th>
                            <th>专业</th>
                            <th>选课时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${students.map(student => `
                            <tr>
                                <td>${student.student_name}</td>
                                <td>${student.student_grade || '-'}</td>
                                <td>${student.student_major || '-'}</td>
                                <td>${new Date(student.selected_at).toLocaleString()}</td>
                                <td>
                                    <span class="badge bg-success">${student.status || '已选'}</span>
                                </td>
                                <td>
                                    <button class="btn btn-outline-danger btn-sm" onclick="dropStudentCourse('${student.selection_id}', '${student.student_id}', '${student.course_id}')">
                                        <i class="fas fa-user-times me-1"></i>退课
                                    </button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;
    }
}

// 学生退课功能
async function dropStudentCourse(selectionId, studentId, courseId) {
    if (!confirm('确定要为此学生退课吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/student-courses/${selectionId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            alert('退课成功！');
            // 重新加载页面数据
            loadCourseDetail(courseId);
            loadEnrolledStudents(courseId);
        } else {
            const error = await response.json();
            throw new Error(error.error || '退课失败');
        }
    } catch (error) {
        console.error('退课失败:', error);
        alert('退课失败: ' + error.message);
    }
}

// 编辑课程
function editCourse(courseId) {
    window.location.href = `/edit-course/${courseId}`;
}

// 删除课程
async function deleteCourse(courseId) {
    if (!confirm('确定要删除这个课程吗？此操作不可恢复。')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/courses/${courseId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            alert('课程删除成功！');
            window.location.href = '/courses';
        } else {
            const error = await response.json();
            throw new Error(error.error || '删除课程失败');
        }
    } catch (error) {
        console.error('删除课程失败:', error);
        alert('删除课程失败: ' + error.message);
    }
}
</script>
{% endblock %}
